<?PHP
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Thu, 1 Jan 1970 01:00:00 GMT"); // Date in the past
error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR);
ini_set('log_errors', '1');
ini_set('error_log', 'php_error.log');
ini_set('display_errors', '1');

include_once("file.common.php");

$path = req('path', 'uploads');
$ajax = req('ajax');
$goto = req('goto');
$filename = req('filename');

$result = FALSE;
$msg = "";
$jFiles = "";
$size = 0;

$path = str_replace("\\", '/', $path);
$filename = str_replace("\\", '/', $filename);
while (substr($path,-1,1) == '/') $path = substr($path, 0, strlen($path)-1);

function getDirFiles($dirpath, $pre, $level, $recur) {
	//
	// Get folder and file lists
	//
	global $totdirs, $totfiles, $totsize, $exists, $hidden;
	$level++;
	$ot = '';
	$numdirs = 0;
	$numfiles = 0;
	$exists = TRUE;
	if (!$dirpath)
		$dirpath = '.';
	$handle = opendir($dirpath);
	if ($handle) {
		$exists = TRUE;
		while (FALSE !== ($file = readdir($handle))) {
			$nm = $dirpath . '/' . $file;
			if (is_dir($nm)) {
				if ($file != '.' && $file != '..') {
					$dirarr[$numdirs] = $file;
					$numdirs++;
				}
			} else {
				if (!is_link($nm) && ($hidden == 'true' || substr($file, 0, 1) != '.')) {
					$filearr[] = $file;
					$numfiles++;
				}
			}
		}
		closedir($handle);
	}

	if ($numdirs > 1)
		sort($dirarr);
	if ($numfiles > 1)
		sort($filearr);

	// Collect file sizes and modification times
	if ($numfiles > 0)
		for ($i = 0; $i < $numfiles; $i++) {
			$nm = $dirpath . '/' . $filearr[$i];
			$sizearr[] = filesize($nm);
			$dts = strftime("%Y-%m-%d %H:%M:%S", filemtime($nm)) . " UTC";
			$timearr[] = strtotime($dts);
			//$timearr[] = gmdate('U', filemtime($nm));
			//$timearr[] = filemtime($nm);
			$uimearr[] = gmdate('"Y-m-d H:i:s",', filemtime($nm));
		}

	if ($numdirs > 0)
		for ($i = 0; $i < $numdirs; $i++) {
			$nm = $pre . $dirarr[$i];
			$ot .= "[";
			$ot .= json_encode($nm) . ",";
			$ot .= "0,";
			$ot .= "0,";
			$ot .= 'true,'; // is folder
			$ot .= $level;
			$ot .= "],\n";
		}
	if ($numfiles > 0)
		for ($i = 0; $i < $numfiles; $i++) {
			$nm = $pre . $filearr[$i];
			$ot .= "[";
			$ot .= json_encode($nm) . ",";
			$ot .= $sizearr[$i] . ",";
			$ot .= $timearr[$i] . ",";
			$ot .= 'false,'; // is not folder
			$ot .= json_encode($uimearr[$i]);
			//$ot .= $level;
			$ot .= "],\n";
			$totsize += $sizearr[$i];
		}
	$totdirs += $numdirs;
	$totfiles += $numfiles;

	if ($recur === TRUE)
		for ($i = 0; $i < $numdirs; $i++) {
			$ot .= getDirFiles($dirpath . '/' . $dirarr[$i], $pre . $dirarr[$i] . '/', $level, $recur);
		}
	return $ot;
}

function getFileList($path, $recur)
{
	return trim(getDirFiles($path, "", 0, $recur), ",\n");
}

function getFileExtension($path)
{
	$gis = getimagesize($path);
	switch ($gis[2])
	{
	case 1: return ".gif";
	case 2: return ".jpg";
	case 3: return ".png";
	case 4: return ".swf";
	case 5: return ".psd";
	case 6: return ".bmp";
	case 7: return ".tiff";
	case 8: return ".tiff";
	case 9: return ".jpc";
	case 10: return ".jp2";
	case 11: return ".jpx";
	case 12: return ".jb2";
	case 13: return ".swc";
	case 14: return ".iff";
	case 15: return ".wbmp";
	case 16: return ".xbm";
	}
	return ".jpg"; // Default to .jpg so it has some extension
}
	
if(array_key_exists('thefile', $_FILES)) {

	if (!$filename)
		$filename = $_FILES['thefile']['name'];

	$ext = getFileExtension($_FILES['thefile']['tmp_name']);
	$ixt = stripos($filename, $ext);
	if ($ixt == FALSE || strrpos($filename, '.') != $ixt)
		$filename .= $ext;
		
	// Validate the uploaded file
	if ($validCredentials !== TRUE)
		$msg = "Invalid credentials";
	else if (strpos($path, '..') !== FALSE || strpos($filename, '..') !== FALSE)
		$msg = "Path cannot contain ..";
	else if($_FILES['thefile']['size'] === 0 || empty($_FILES['thefile']['tmp_name'])) {
		$msg = "No file was selected.";
	} else if($_FILES['thefile']['size'] > 50000000) {
		$msg = "The file was too large.";
	} else if($_FILES['thefile']['error'] !== UPLOAD_ERR_OK) {
		// There was a PHP error
		$msg = "There was an error uploading.";
	} else {

		$name = webPath($path, $filename);
		
		// Create uploads directory if necessary
		if(!file_exists($path)) @mkdir($path, 0777, true);

		// Move the file
		if(move_uploaded_file($_FILES['thefile']['tmp_name'], $name)) {
			$size = filesize($name);
			$msg = "File \"$name\" was uploaded successfully! (size $size)";
			$result = TRUE;
		} else {
			$msg = "There was an error moving the file.";
		}
	}

	$ee = '';
	if ($callback)
		$ee .= "$callback({\n";
	else
		$ee .= "{\n";
	$ee .= '"result":' . json_encode($result) . ",\n";
	$ee .= '"path":' . json_encode($path) . ",\n";
	$ee .= '"file":' . json_encode($name) . ",\n";
	$ee .= '"fullName":' . json_encode($name) . ",\n";
	$ee .= '"fileSize":' . json_encode($size) . ",\n";
	$ee .= '"msg":' . json_encode($msg) . ",\n";
	$ee .= '"host":' . json_encode($_SERVER['SERVER_NAME']) . ",\n";
	if ($devserver) {
		$ee .= '"cwd":' . json_encode(getcwd()) . ",\n";
		$ee .= '"root":' . json_encode($_SERVER['DOCUMENT_ROOT']) . ",\n";
	}
	$ee .= '"end":true' . "\n";
	if ($callback)
		$ee .= "})";
	else
		$ee .= "}";

	if ($ajax)
	{
		autoheader();
		echo $ee;
		exit(0);
	}
	else if ($goto)
	{
		$redirectData .= "{\"fullName\":\"$name\"}";
		header('Content-type: text/html');
		$ot = "";
		$ot .= "<html><head></head><body>";
		$ot .= "<script type='text/javascript'>";
		$ot .= "sessionStorage['RedirectData'] = '$redirectData';";
		$ot .= "location.href = '$goto';";
		$ot .= "</script>";
		$ot .= "</body></html>";
		echo $ot;
		exit(0);
	}
}

$jFiles = getFileList('.', TRUE);

?>
<html>
<head>
<title>Upload file</title>
<style>
.dir:hover { cursor: pointer; background-color: #CCF; }
</style>
</head>
<body style="font-family:calibri;">
<blockquote>
	<div style="font-family:courier new;color:blue"><?PHP echo($msg)?></div>
</blockquote>
<form enctype="multipart/form-data" action="upload.php" method="post">
	<input type="hidden" name="MAX_FILE_SIZE" value="50000000">
	<blockquote>
		<h3>Upload a file:</h3>
		Password <input id="password" type="password" name="password" value="<?PHP echo($password) ?>" size="20">
		<button onclick="sessionStorage['FileUploadPassword'] = ''; document.getElementById('password').value = ''; return false;">reset</button>
		<br>
		Path <input id="path" type="text" name="path" value="<?PHP echo($path) ?>" size="40"> <span id="dirlist" style="color:blue;font-size: 8pt"></span><br>
		File <input type="file" size="20" name="thefile"><br>
		<input type="hidden" name="ajax" value="false">
		<blockquote>
			<input type="submit" name="Submit" value="Send">
		</blockquote>
	</blockquote>
</form>
<script type="text/javascript">
	var pw = sessionStorage['FileUploadPassword'];
	if (pw) document.getElementById('password').value = pw;
	pw = document.getElementById('password').value || "<?PHP echo($password) ?>";
	sessionStorage['FileUploadPassword'] = pw;
	
	var files = [<?PHP echo($jFiles) ?>];
	var topdirs = '';
	for (var i=0; i < files.length; i++)
	{
		var comma = i ? ', ' : '';
		if (files[i][3] == true && files[i][4] < 4)
			topdirs += comma + "<span class='dir' onclick='document.getElementById(\"path\").value = \"" + files[i][0] +  "\"'>" + files[i][0] + "</span>";
	}
	
	document.getElementById('dirlist').innerHTML = topdirs;
</script>
</body>
</html>